package com.jash.lifxdemo;

import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.jash.lifxdemo.databinding.ActivityContentBinding;
import com.jash.lifxdemo.entities.ContentEntity;
import com.jash.lifxdemo.entities.Entity;
import com.jash.lifxdemo.utils.NetService;

import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ContentActivity extends AppCompatActivity implements Callback<Entity<ContentEntity>> {
    private ActivityContentBinding binding;
    private long id;
    private NetService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_content);
        id = getIntent().getLongExtra("id", 0);
        service = ((BaseApplication) getApplication()).getService();
        service.getContent(id).enqueue(this);
    }

    @Override
    public void onResponse(Call<Entity<ContentEntity>> call, Response<Entity<ContentEntity>> response) {
        String content = response.body().getData().getText_content();
        List<String> images = response.body().getData().getText_images();
        Matcher matcher = Pattern.compile("\\$\\{lx-(\\w+)-?(\\d*)\\}").matcher(content);
        StringBuffer buffer = new StringBuffer("<style>img{max-width:100%}</style>");
        while (matcher.find()) {
            switch (matcher.group(1)) {
                case "br":
                    matcher.appendReplacement(buffer, "<br/>");
                    break;
                case "image":
                    matcher.appendReplacement(buffer, String.format(Locale.getDefault(), "<img src=\"%s\"/>", images.get(Integer.parseInt(matcher.group(2)))));
                    break;
            }
        }
        matcher.appendTail(buffer);
        binding.web.loadData(buffer.toString(), "text/html; charset=utf-8;", "UTF-8");
    }

    @Override
    public void onFailure(Call<Entity<ContentEntity>> call, Throwable t) {

    }
}
